<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\WeChatController;
class SendTemp extends Command
{
    /**发送模板消息
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'send:temp';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    protected $app;
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }


    public function handle(){
        set_time_limit(50);
        //查询数据库中待发送的模板消息,每次取5条
        $send_temp = DB::table('TEMPLATE_MSGS')->whereIn('send_status',[0])
                        ->orderBy('id','DESC')->limit(5)->get();

        $wechat_controller = new WeChatController();
        if($send_temp){
            foreach($send_temp as $value){
                //模板消息发送url
                $url = "https://Api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $wechat_controller->get_access_token($value->appid);
                //模板消息数据
                $send = [
                    'touser' => $value->open_id,
                    'template_id' => $value->template_id,
                    'url' => $value->url,
                    'data' => json_decode($value->data,1)
                ];

                error_log(date('Y-m-d H:i:s') . ' 模板消息数据' . print_r($send,1) . "\n",3,base_path() . '/storage/logs/'.$value->appid.'.log');

                $res = curl_post($url,$send);

                error_log(date('Y-m-d H:i:s') . ' 模板消息发送结果' . $res . "\n",3,base_path() . '/storage/logs/'.$value->appid.'.log');

                $res = json_decode($res,1);

                if($res['errcode'] == 0){
                    DB::table('TEMPLATE_MSGS')->where('id',$value->id)
                        ->update(['send_status'=>5,'msgid'=>$res['msgid']]);
                }else{
                    DB::table('TEMPLATE_MSGS')->where('id',$value->id)
                        ->update(['send_status'=>2,'errmsg'=>$res['errmsg']]);
                }
            }
        }
    }
}
